<?php

class DifferenceGamesController extends DifferenceAppController{
	protected $_allowActions = array();
	protected $_denyActions = array('randgame');
	public function index(){
		Utils::loadModels($this, array('DifferenceGame'));
		$conds = array(
				'DifferenceGame.status' => DifferenceGame::STATUS_PUBLIC,
			);
		Utils::loadComponents($this, array('Difference.DifferenceLogic'));
		$player = $this->DifferenceLogic->syncPlayer(
			array(
				'DifferencePlayer' => array(
					'email' => $this->Auth->user('email')
				)
			)
		);
		$this->paginate = array(
			'conditions' => $conds,
			'limit' => 12,
			'order' => 'DifferenceGame.id DESC',
		);
		$data = $this->paginate('DifferenceGame');
		if(!empty($player)){
			$gameIds = array();
			foreach($data as &$g){
				$gameIds[] = $g['DifferenceGame']['id'];
			}

			// query to get score
			Utils::loadModels($this, array('Difference.DifferenceScore'));
			$scores = $this->DifferenceScore->find('all', array(
				'conditions' => array(
					'player_id' => $player['DifferencePlayer']['id']
				)
			));
			$scoreMap = array();
			foreach($scores as &$s){
				$scoreMap[$s['DifferenceScore']['game_id']] = $s;
			}

			// do map
			foreach($data as &$g){
				$gameId = $g['DifferenceGame']['id'];
				$g['DifferenceScore'] = isset($scoreMap[$gameId]) ? $scoreMap[$gameId]['DifferenceScore'] : array();
			}
		}
		$this->set('title_for_layout', 'Trò chơi - Tìm điểm khác nhau');
		$this->set(compact('data'));
		$this->set('player', $player);
	}

	function index_permanently_moved(){
		header('Status-Code: 301');
		header('HTTP/1.1 301 Moved Permanently');
		$this->redirect(array('action' => 'index'));
		exit(0);
	}

	function view($seo = null) {
		$hash = md5($seo, true);
		Utils::loadComponents($this, array('Difference.DifferenceLogic'));
		$data = $this->DifferenceLogic->viewGame($hash);
		if(empty($data['DifferenceGame']['different_points'])){
			$data['DifferenceGame']['different_points'] = json_encode(array());
		}

		// no game, redirect to home
		if(empty($data['DifferenceGame']['name'])){
			$this->redirect(array('controller' => 'difference_games', 'action' => 'index'));
		}

		// !important: start the game in session
		$this->_startGame($data['DifferenceGame']);
		$this->set('title_for_layout', 'Trò chơi - Tìm điểm khác nhau - ' . $data['DifferenceGame']['name']);
		$this->set(compact('data'));
	}

	function view_permanently_moved($seo = null){
		header('Status-Code: 301');
		header('HTTP/1.1 301 Moved Permanently');
		$this->redirect(array('action' => 'view', $seo));
		exit(0);
	}

	function randgame(){
		Utils::loadComponents($this, array('Difference.DifferenceLogic'));
		$player = $this->DifferenceLogic->syncPlayer(
			array(
				'DifferencePlayer' => array(
					'email' => $this->Auth->user('email')
				)
			)
		);
		if(!empty($this->data['Play']['resolved'])){
			// get playing game
			$info = $this->_getGameInfo();

			// try to end playing game
			if(!empty($info['DifferenceGame']['id'])){
				$game = $info['DifferenceGame'];
				Utils::loadModels($this, array('Difference.DifferenceScore'));
				// this user resolved this game in 1 year before ?
				$scored = $this->DifferenceScore->find('first', array(
					'fields' => array(
						'id','resolved'
					),
					'conditions' => array(
						'player_id' => $player['DifferencePlayer']['id'],
						'game_id' => $game['id'],
					)
				));
				if(empty($scored) || empty($scored['resolved'])){
					$scored = array(
						'DifferenceScore' => array(
							'player_id' => $player['DifferencePlayer']['id'],
							'game_id' => $game['id'],
							'marked_differences' => count(json_decode($game['different_points'])),
							'created' => $info['created'],
							'resolved' => date('Y-m-d H:i:s')
						)
					);
					$this->DifferenceScore->saveIt($scored);
				}
			}
			$this->_endGame();

			if($this->isAjax()){
				$this->response['status'] = 0;
				$this->sendAjax();
			}
		}

		// try to get a new game
		$data['DifferencePlayer'] = $player['DifferencePlayer'];
		$game = $this->DifferenceLogic->randNotPlayedGame($data);
		$url = array('plugin' => 'difference', 'controller' => 'difference_games', 'action' => 'view', $game['DifferenceGame']['seo_name']);
		$this->redirect($url);
	}

	private function _startGame($data){
		$this->Session->write('Play.created', date('Y-m-d H:i:s'));
		$this->Session->write('Play.DifferenceGame', $data);
	}

	private function _getGameInfo(){
		return array(
			'created' => $this->Session->read('Play.created'),
			'DifferenceGame' => $this->Session->read('Play.DifferenceGame')
		);
	}

	private function _endGame(){
		$this->Session->write('Play.created', null);
		$this->Session->write('Play.DifferenceGame', null);
	}

	public function system_index(){
		Utils::loadModels($this, array('DifferenceGame'));
		$this->paginate = array(
			'conditions' => array(),
			'limit' => 20,
			'order' => 'DifferenceGame.id DESC',
		);
		$data = $this->paginate('DifferenceGame');
		$this->set(compact('data'));
	}

	public function system_edit($id = null){
		Utils::loadComponents($this, array('Difference.DifferenceLogic'));
		if($this->isPost()){
			$this->data['DifferencePlayer']['email'] = $this->Auth->user('email');
			$this->data['DifferenceGame']['seo_md5_raw'] = md5($this->data['DifferenceGame']['seo_name'], true);
			$this->data['DifferenceGame']['id'] = $id;
			$points = explode(';',$this->data['DifferenceGame']['different_points']);
			$points2 = array();
			foreach($points as $point){
				$vals = explode(',', $point);
				if(count($vals) < 4) continue;
				$points2[] = array(
					'x' => $vals[0],
					'y' => $vals[1],
					'w' => $vals[2],
					'h' => $vals[3]
				);
			}
			$this->data['DifferenceGame']['different_points'] = $points2;
			$result = $this->DifferenceLogic->saveGame($this->data);
			if(!$result['status']){
				$this->Session->setFlash('Tạo game thành công');
				$this->redirect('/system/difference/difference_games');
			} else {
				$this->Session->setFLash($result['message']);
			}
		} else {
			$this->data = $this->DifferenceGame->findById($id);
			if(empty($this->data['DifferenceGame']['different_points'])){
				$this->data['DifferenceGame']['different_points'] = json_encode(array());
			}
		}
	}
}